package cn.aimee.permission.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;
import cn.aimee.permission.util.screen.ScreenUtil;
import cn.aimee.permission.util.string.StringUtil;
import cn.aimee.permission.util.uiunit.UIUnitConverUtil;

/**
 * @author: czh
 * @time: 2021\8\31 0031
 */
public class CustomTipDialog extends Dialog {

    private Activity mActivity;
    public static CountDownTimer countDownTimer;
    public static final int DEFAULT_DOWN_TIME = 3 * 1000;
    public static final int DEFAULT_TIME_INTERVAL = 1 * 1000;

    public CustomTipDialog(Activity activity) {
        this(activity, cn.aimee.permission.R.style.dialog);
    }

    public CustomTipDialog(Activity activity, int theme) {
        super(activity, theme);
        mActivity = activity;
    }

    public static class Builder implements LifecycleEventObserver{
        private Activity activity;

        private int gravityValue = Gravity.CENTER;
        private LinearLayout.LayoutParams textLayoutParams;

        private String titleName;
        private String message;
        private String negativeButtonText = null;
        private Drawable negativeButtonBackground;
        private int negativeButtonBackgroundId;
        private String positiveButtonText = null;
        private Drawable positiveButtonBackground;
        private int positiveButtonBackgroundId;
        private CustomTipDialog customTipDialog;

        private DialogInterface.OnClickListener negativeButtonClickListener;
        private DialogInterface.OnClickListener positiveButtonClickListener;

        public Builder(Activity activity) {
            this.activity = activity;
            if (null == activity)
                return;
            negativeButtonBackgroundId = cn.aimee.permission.R.drawable.btn_round_gray_two;
            positiveButtonBackgroundId = cn.aimee.permission.R.drawable.btn_round_blue_two;
            negativeButtonBackground = activity.getResources().getDrawable(cn.aimee.permission.R.drawable.btn_round_gray_two);
            positiveButtonBackground = activity.getResources().getDrawable(cn.aimee.permission.R.drawable.btn_round_blue_two);
        }

        public Builder setTitle(String titleName) {
            this.titleName = titleName;
            return this;
        }

        public Builder setTitle(int titleName) {
            this.titleName = activity.getText(titleName).toString();
            return this;
        }

        public Builder setMessage(String message) {
            this.message = message;
            return this;
        }

        public Builder setMessage(int message, int gravity) {
            return setMessage(activity.getText(message).toString(), gravity);
        }

        /**
         * 可自定义text的对齐属性
         * @param message
         * @param gravity 使用Gravity属性赋值（Gravity.NO_GRAVITY, Gravity.CENTER_HORIZONTAL...）
         * @return
         */
        public Builder setMessage(String message, int gravity) {
            this.message = message;
            gravityValue = gravity;

            // textView中文字显示默认为居中，所有在这里只设置除居中以外的属性
            if (gravityValue != Gravity.CENTER) {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                int margin = UIUnitConverUtil.dipToPx(activity, 20);
                params.setMargins(margin, 0, margin, 0);
                textLayoutParams = params;
            }
            return this;
        }

        /**
         * set the Dialog message from resource
         * @param message
         * @return
         */
        public Builder setMessage(int message) {
            if (null != activity) {
                this.message = activity.getText(message).toString();
            }
            return this;
        }


        /**
         * 设置按钮的点击事件，默认按钮文字为“确定”
         * @param listener
         * @return
         */
        public Builder setNegativeButton(DialogInterface.OnClickListener listener) {
            negativeButtonText = activity.getText(cn.aimee.permission.R.string.button_ok).toString();
            negativeButtonClickListener = listener;
            return this;
        }

        /**
         * 设置按钮的点击事件，可自定义按钮文字
         * @param negativeButtonText ： 按钮文字
         * @param listener
         * @return
         */
        public Builder setNegativeButton(String negativeButtonText, DialogInterface.OnClickListener listener) {
            this.negativeButtonText = negativeButtonText;
            negativeButtonClickListener = listener;
            return this;
        }

        public Builder setNegativeButton(int negativeButtonText, DialogInterface.OnClickListener listener) {
            this.negativeButtonText = activity.getText(negativeButtonText).toString();
            negativeButtonClickListener = listener;
            return this;
        }

        public Builder setNegativeButtonBackground(int background) {
            negativeButtonBackgroundId = background;
            this.negativeButtonBackground = activity.getResources().getDrawable(background);
            return this;
        }

        public Builder setNegativeButtonBackground(Drawable background) {
            this.negativeButtonBackground = background;
            return this;
        }

        public Builder setPositiveButton(String positiveButtonText, DialogInterface.OnClickListener listener) {
            this.positiveButtonText = positiveButtonText;
            positiveButtonClickListener = listener;
            return this;
        }

        public Builder setPositiveButton(int positiveButtonText, DialogInterface.OnClickListener listener) {
            this.positiveButtonText = activity.getText(positiveButtonText).toString();
            positiveButtonClickListener = listener;
            return this;
        }

        public Builder setPositiveButtonBackground(int background) {
            positiveButtonBackgroundId = background;
            this.positiveButtonBackground = activity.getResources().getDrawable(background);
            return this;
        }

        public Builder setPositiveButtonBackground(Drawable background) {
            this.positiveButtonBackground = background;
            return this;
        }

        public CustomTipDialog create() {
            int wh[] = ScreenUtil.getDeviceWH(activity);
            int width = wh[0] - UIUnitConverUtil.dipToPx(activity, 80);

            View view = LayoutInflater.from(activity).inflate(cn.aimee.permission.R.layout.dialog_custom_tip, null);
            customTipDialog = new CustomTipDialog(activity, cn.aimee.permission.R.style.dialog);
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
            customTipDialog.addContentView(view, layoutParams);
            customTipDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (null != countDownTimer) {
                        countDownTimer.cancel();
                        countDownTimer = null;
                    }
                }
            });

            initView(view, customTipDialog);
            customTipDialog.setContentView(view);
            ((LifecycleOwner)activity).getLifecycle().addObserver(this);
            customTipDialog.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    ((LifecycleOwner)activity).getLifecycle().removeObserver(Builder.this);
                }
            });
            return customTipDialog;
        }

        private void initView(View view, final CustomTipDialog customTipDialog) {
            LinearLayout llTitle = (LinearLayout) view.findViewById(cn.aimee.permission.R.id.ll_title);
            TextView tvTitle = (TextView) view.findViewById(cn.aimee.permission.R.id.tv_title);
            if (StringUtil.isNotEmpty(titleName)) {
                llTitle.setVisibility(View.VISIBLE);
                tvTitle.setText(titleName);
            }

            Button btnNegative = (Button) view.findViewById(cn.aimee.permission.R.id.btn_negative);
            if (null != negativeButtonText) {
                btnNegative.setVisibility(View.VISIBLE);
                btnNegative.setText(negativeButtonText);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    btnNegative.setBackground(negativeButtonBackground);
                } else {
                    btnNegative.setBackgroundResource(negativeButtonBackgroundId);
                }
                if (null != negativeButtonClickListener) {
                    btnNegative.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            negativeButtonClickListener.onClick(customTipDialog, DialogInterface.BUTTON_NEGATIVE);

                        }
                    });
                }
            } else {
                btnNegative.setVisibility(View.GONE);
            }

            Button btnPositive = (Button) view.findViewById(cn.aimee.permission.R.id.btn_positive);
            if (null != positiveButtonText) {
                btnPositive.setVisibility(View.VISIBLE);
                btnPositive.setText(positiveButtonText);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    btnPositive.setBackground(positiveButtonBackground);
                } else {
                    btnNegative.setBackgroundResource(positiveButtonBackgroundId);
                }
                if (null != positiveButtonClickListener) {
                    btnPositive.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            positiveButtonClickListener.onClick(customTipDialog, DialogInterface.BUTTON_NEGATIVE);

                        }
                    });
                }
            } else {
                btnPositive.setVisibility(View.GONE);
            }

            LinearLayout llButtons = (LinearLayout) view.findViewById(cn.aimee.permission.R.id.ll_buttons);
            if(btnNegative.getVisibility() == View.GONE && btnPositive.getVisibility() == View.GONE) {
                llButtons.setVisibility(View.GONE);
            } else {
                llButtons.setVisibility(View.VISIBLE);
                llButtons.setPadding(30, 30, 30, 30);
            }

            if (null != message) {
                TextView tv_message = (TextView) view.findViewById(cn.aimee.permission.R.id.tv_message);
                if (gravityValue != Gravity.CENTER) {
                    tv_message.setLayoutParams(textLayoutParams);
                    tv_message.setGravity(gravityValue);
                }
                tv_message.setText(message);
            }
        }

        @Override
        public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
            if (event == Lifecycle.Event.ON_DESTROY) {
                if (null != customTipDialog &&customTipDialog.isShowing()) {
                    customTipDialog.dismiss();
                }
            }
        }
    }

    public void startDefaultDownTime() {
        startDownTime(DEFAULT_DOWN_TIME, DEFAULT_TIME_INTERVAL);
    }

    public void startDownTime(long millisInFuture) {
        startDownTime(millisInFuture, DEFAULT_TIME_INTERVAL);
    }

    public void startDownTime(long millisInFuture, long countDownInterval) {
        countDownTimer = new CountDownTimer(millisInFuture, countDownInterval) {
            @Override
            public void onTick(long millisUntilFinished) {}

            @Override
            public void onFinish() {
                if (!mActivity.isFinishing())
                    dismiss();
            }
        };
        countDownTimer.start();
    }

}